import { getToken } from "@/utils/auth";
import { ElMessage } from "element-plus";
import { emitter } from "@/utils/bus";
import host from "@/utils/host";
import store from "@/store";

let websocket = null;
let reconnectTimer = null;
let heartbeatTimer = null;
const HEARTBEAT_INTERVAL = 30000; // 30 seconds
const RECONNECT_INTERVAL = 5000; // 5 seconds
const MAX_RECONNECT_ATTEMPTS = 5;
let reconnectAttempts = 0;
let userId = null;

const getMessage = (message) => {
  if (message.data !== "Ping") {
    ElMessage({
      message: `${message.data}`,
      type: "success",
      duration: 3000,
    });
    emitter.emit("updateExamList");
    // store里的试卷数量+1
    store.dispatch("learn/setPaperCount", store.getters.paperCount + 1);
  }
};

const startHeartbeat = () => {
  clearInterval(heartbeatTimer);
  heartbeatTimer = setInterval(() => {
    if (websocket && websocket.readyState === WebSocket.OPEN) {
      websocket.send("Pong");
    }
  }, HEARTBEAT_INTERVAL);
};

const reconnect = () => {
  if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
    console.error("Maximum reconnection attempts reached");
    clearTimeout(reconnectTimer);
    return;
  }
  
  reconnectAttempts++;
  console.log(`Attempting to reconnect (${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})...`);
  
  clearTimeout(reconnectTimer);
  reconnectTimer = setTimeout(() => {
    setupWebSocket(userId);
  }, RECONNECT_INTERVAL);
};

const setupWebSocket = (userIdParam) => {
  // Store userId for reconnection
  userId = userIdParam;
  
  // Clear any existing connection
  closeWebSocket();
  
  //判断当前浏览器是否支持WebSocket
  if ("WebSocket" in window) {
    //改成你的地址
    websocket = new WebSocket(
      `ws:/${host}:9080/api/websocket/${userId}`
    );
  } else {
    alert("当前浏览器 Not support websocket");
    return null;
  }

  //连接发生错误的回调方法
  websocket.onerror = function () {
    console.error("WebSocket连接发生错误");
    reconnect();
  };

  //接收到消息的回调方法
  websocket.onmessage = function (event) {
    getMessage(event);
  };
  
  // Connection opened
  websocket.onopen = function() {
    console.log("WebSocket connection established");
    reconnectAttempts = 0; // Reset reconnect attempts on successful connection
    startHeartbeat();
  };
  
  // Connection closed
  websocket.onclose = function() {
    clearInterval(heartbeatTimer);
    reconnect();
  };


  return websocket;
};

const closeWebSocket = () => {
  if (websocket) {
    websocket.close();
    websocket = null;
  }
  clearInterval(heartbeatTimer);
  clearTimeout(reconnectTimer);
};

export { setupWebSocket, closeWebSocket };
